package com.beagle.njddapp.ui.activity.owner;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.bean.UploadBean;
import com.beagle.njddapp.bean.ZdBean;
import com.beagle.njddapp.bean.owner.NjBean;
import com.beagle.njddapp.bean.owner.NongJiBean;
import com.beagle.njddapp.ui.presenter.NjUpdatePresenter;
import com.beagle.njddapp.ui.view.NjUpdateView;
import com.beagle.njddapp.utils.GlideEngine;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.utils.Utils;
import com.beagle.njddapp.weight.dialog.ZdDIalog;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import butterknife.BindView;
import butterknife.OnClick;

import static com.beagle.njddapp.ui.activity.BasicUserInfoActivity.CHOOSE_IMG_BACK;
import static com.beagle.njddapp.ui.activity.BasicUserInfoActivity.CHOOSE_IMG_FRONT;

/**
 * @author hxx
 * @date 2021-03-22 22:22
 */
public class DeviceUpdateActivity extends BaseMvpActivity<NjUpdateView, NjUpdatePresenter> implements NjUpdateView, ZdDIalog.ZdDialogItemClickLisenter, View.OnClickListener {

    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.common_container)
    RelativeLayout container;
    @BindView(R.id.common_tv_right)
    TextView tvRight;
    @BindView(R.id.ed_device_number)
    TextView edNumber;
    @BindView(R.id.ed_device_creator)
    EditText edChangjia;
    @BindView(R.id.ed_device_addressr)
    EditText eddizhi;
    @BindView(R.id.tv_pinpai)
    TextView tvPinPai;
    @BindView(R.id.tv_type)
    TextView tvLeiXing;
    @BindView(R.id.tv_xinghao)
    TextView tvxinghao;
    @BindView(R.id.ed_device_bianhao)
    EditText edBianhao;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ed_device_gauche)
    EditText edGuache;
    @BindView(R.id.ed_device_jxs)
    EditText edJxs;
    @BindView(R.id.ed_device_jsx_place)
    EditText edJxsPlace;
    @BindView(R.id.ed_device_youliang)
    EditText edYouLiang;
    @BindView(R.id.ed_device_zd_number)
    EditText edZd;
    @BindView(R.id.ed_device_size)
    EditText edSize;
    @BindView(R.id.ed_device_zhiliang)
    EditText edzhiliang;
    @BindView(R.id.ed_device_gonglv)
    EditText edGonglv;
    @BindView(R.id.ll_device_iv)
    LinearLayout lliv1;
    @BindView(R.id.iv1)
    ImageView ivFront;
    @BindView(R.id.iv2)
    ImageView ivback;
    @BindView(R.id.ed_card_number)
    EditText edCardNumber;
    private NjBean njBean;
    private List<View> imgViews;
    private List<String> paths;
    private static final int CHOOSE_IMG = 1004;
    private AtomicInteger size;
    private String type;
    private ZdDIalog zdDIalog;
    private int nowClick = 1;
    private String type_id,brand_id="",size_id="";
    private String brand_parentID="",size_parentID;

    @Override
    public int getLayoutId() {
        return R.layout.activity_nj_update;
    }

    @Override
    public void init() {
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        tvTitle.setText("农机设备修改");
        tvRight.setText("完成");
        njBean = (NjBean) getIntent().getSerializableExtra("data");
        edNumber.setText(njBean.getMeshNum());
        edChangjia.setText(njBean.getMfrs());
        edJxs.setText(njBean.getAgentName());
        eddizhi.setText(njBean.getMfrsAddress());
        tvPinPai.setText(njBean.getBrandName());
        tvLeiXing.setText(njBean.getTypeName());
        tvxinghao.setText(njBean.getSizeName());
        edBianhao.setText(njBean.getSerialNo());
        edJxsPlace.setText(njBean.getAgentArea());
        brand_parentID=njBean.getType();
        size_parentID=njBean.getBrand();
        type_id=njBean.getType();
        brand_id=njBean.getBrand();
        size_id=njBean.getSize();
        edYouLiang.setText(njBean.getTankCapacity() + "");
        edZd.setText(njBean.getLotId());
        edSize.setText(njBean.getDimensions());
        edzhiliang.setText(njBean.getMass());
        edGonglv.setText(njBean.getPower());
        edGuache.setText(njBean.getTrailerNum());
        edCardNumber.setText(njBean.getLicenseNum());
        tvTime.setText(njBean.getProductionDate());
        Glide.with(this).applyDefaultRequestOptions(new RequestOptions().placeholder(R.mipmap.register_btn_drivea)).load(njBean.getFrontLicenseUrl()).into(ivFront);
        Glide.with(this).applyDefaultRequestOptions(new RequestOptions().placeholder(R.mipmap.register_btn_driveb)).load(njBean.getBackLicenseUrl()).into(ivback);
        paths = new ArrayList<>();
        imgViews=new ArrayList<>();
        addIv(njBean.getFrontPictureUrl());
        addIv(njBean.getSidePictureUrl());
        addIv(njBean.getBackPictureUrl());
        if (!TextUtils.isEmpty(njBean.getFrontPictureUrl())){
            paths.add(njBean.getFrontPictureUrl());
        }
        if (!TextUtils.isEmpty(njBean.getSidePictureUrl())){
            paths.add(njBean.getSidePictureUrl());
        }
        if (!TextUtils.isEmpty(njBean.getBackPictureUrl())){
            paths.add(njBean.getBackPictureUrl());
        }
        if (paths.size()!=3){
            addFirstIv();
        }
        size=new AtomicInteger(0);

    }

    private void addIv(Uri uri) {
        if (paths.size() == 3) {
            lliv1.removeAllViews();
            imgViews.add(imgViews.size() - 1, getImgView(uri));
            imgViews.remove(imgViews.size() - 1);
            for (View view : imgViews) {
                lliv1.addView(view);
            }
        } else {
            lliv1.removeAllViews();
            imgViews.add(imgViews.size() - 1, getImgView(uri));
            for (View view : imgViews) {
                lliv1.addView(view);
            }
        }
    }

    private void addIv(String purl) {
        if (TextUtils.isEmpty(purl)){
            return;
        }
        if (paths.size() == 3) {
            imgViews.remove(imgViews.size() - 1);
            lliv1.removeAllViews();
            imgViews.add(getImgView(purl));
            for (View view : imgViews) {
                lliv1.addView(view);
            }
        } else {
            lliv1.removeAllViews();
            imgViews.add(getImgView(purl));
            for (View view : imgViews) {
                lliv1.addView(view);
            }
        }
    }

    public View getImgView(Uri uri) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_add_img, null);
        view.setTag(uri);
        ImageView ivimg = view.findViewById(R.id.iv_img);
        Glide.with(this).load(uri).into(ivimg);
        ImageView ivcancle = view.findViewById(R.id.iv_cancle);
        ivcancle.setVisibility(View.VISIBLE);
        ImageView ivadd = view.findViewById(R.id.iv_add);
        ivadd.setVisibility(View.GONE);
        ivcancle.setOnClickListener(this);
        ivcancle.setTag(uri);
        return view;
    }

    public View getImgView(String uri) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_add_img, null);
        view.setTag(uri);
        ImageView ivimg = view.findViewById(R.id.iv_img);
        Glide.with(this).load(uri).into(ivimg);
        ImageView ivcancle = view.findViewById(R.id.iv_cancle);
        ivcancle.setVisibility(View.VISIBLE);
        ImageView ivadd = view.findViewById(R.id.iv_add);
        ivadd.setVisibility(View.GONE);
        ivcancle.setOnClickListener(this);
        ivcancle.setTag(uri);
        return view;
    }


    @Override
    public NjUpdateView getMvpView() {
        return this;
    }

    @Override
    public NjUpdatePresenter createPresenter() {
        return new NjUpdatePresenter();
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(message);
        size=new AtomicInteger(0);
    }

    @OnClick({R.id.common_back_iv, R.id.common_tv_right, R.id.tv_pinpai, R.id.tv_type, R.id.tv_xinghao, R.id.tv_time, R.id.iv1, R.id.iv2})
    public void onMyCLick(View view) {
        switch (view.getId()) {
            case R.id.common_back_iv:
                onBackPressed();
                break;
            case R.id.common_tv_right:

                if (njBean.getHasMeshNum()==0){
                    if (TextUtils.isEmpty(edNumber.getText().toString()) || TextUtils.isEmpty(tvPinPai.getText().toString())
                            || TextUtils.isEmpty(tvLeiXing.getText().toString()) || TextUtils.isEmpty(tvxinghao.getText().toString()) ||
                            TextUtils.isEmpty(edBianhao.getText().toString()) || TextUtils.isEmpty(tvTime.getText().toString())) {
                        ToastUtils.showShort("请填写完整信息");
                        return;
                    }
                    if (TextUtils.isEmpty(edYouLiang.getText().toString())||
                            TextUtils.isEmpty(edzhiliang.getText().toString())){
                        ToastUtils.showShort("请填写完整信息");
                        return;
                    }
                }
                njBean.setMeshNum(edNumber.getText().toString());
                njBean.setMfrs(edChangjia.getText().toString());
                njBean.setMfrsAddress(eddizhi.getText().toString());
                njBean.setBrand(brand_id);
                njBean.setType(type_id);
                njBean.setSize(size_id);
                njBean.setProductionDate(tvTime.getText().toString());
                njBean.setSerialNo(edBianhao.getText().toString());
                njBean.setTrailerNum(edGuache.getText().toString());
                njBean.setAgentName(edJxs.getText().toString());
                njBean.setAgentArea(edJxsPlace.getText().toString());
                njBean.setTankCapacity(edYouLiang.getText().toString());
                njBean.setDimensions(edSize.getText().toString());
                njBean.setLotId(edZd.getText().toString());
                njBean.setMass(edzhiliang.getText().toString());
                if (!TextUtils.isEmpty(edGonglv.getText().toString())){
                    njBean.setPower(edGonglv.getText().toString());
                }
                njBean.setLicenseNum(edCardNumber.getText().toString());
                if (paths.size()>0){
                    for (int i=0;i<paths.size();i++){
                        presenter.upload(paths.get(i),i);
                    }
                }else {
                    presenter.updateMeshBase(njBean);
                }
                break;
            case R.id.tv_pinpai:
                if (TextUtils.isEmpty(tvLeiXing.getText().toString())) {
                    ToastUtils.showShort("请先选择类型");
                    return;
                }
                type = "2";
                nowClick = 2;
                presenter.queryDictList(type, brand_parentID);
                break;
            case R.id.tv_type:
                type = "1";
                nowClick = 1;
                presenter.queryDictList(type, "");
                break;
            case R.id.tv_xinghao:
                if (TextUtils.isEmpty(tvPinPai.getText().toString())) {
                    ToastUtils.showShort("请先选择品牌");
                    return;
                }
                type = "3";
                nowClick = 3;
                presenter.queryDictList(type, size_parentID);
                break;
            case R.id.tv_time:
                chooseTime();
                break;
            case R.id.iv1:
                Matisse.from(this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG_FRONT);

                break;
            case R.id.iv2:
                Matisse.from(this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG_BACK);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == CHOOSE_IMG_FRONT) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                Glide.with(this).load(mSelected.get(0)).into(ivFront);
                presenter.upload(Utils.getPathFromUri(getApplicationContext(), mSelected.get(0)), 4);
            }
        } else if (requestCode == CHOOSE_IMG_BACK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                Glide.with(this).load(mSelected.get(0)).into(ivback);
                presenter.upload(Utils.getPathFromUri(getApplicationContext(), mSelected.get(0)), 5);

            }
        } else if (requestCode == CHOOSE_IMG) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                paths.add(Utils.getPathFromUri(getApplicationContext(), mSelected.get(0)));
                addIv(mSelected.get(0));
            }
        }
    }

    private void chooseTime() {
        Calendar calendar = Calendar.getInstance();
       DatePickerDialog datePickerDialog= new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String monthStr;
                if (month < 9) {
                    monthStr = "0" + (month + 1);
                } else {
                    monthStr = (month + 1) + "";
                }
                tvTime.setText(year + "-" + monthStr + "-" + dayOfMonth);
                njBean.setCreateTime(year + "-" + monthStr + "-" + dayOfMonth);
            }
        }
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
        datePickerDialog.show();

    }

    @Override
    public void showZd(List<ZdBean> items) {
        if (zdDIalog == null) {
            zdDIalog = new ZdDIalog(this);
            zdDIalog.setZdDialogItemClickLisenter(this);
        }
        zdDIalog.show();
        zdDIalog.setZdBeanList(items);
    }

    @Override
    public void uploadSuccess(UploadBean data, int index) {
        if (index == 4) {
            njBean.setFrontLicenseUrl(data.getVisitURL());
        } else if (index == 5) {
            njBean.setBackLicenseUrl(data.getVisitURL());
        } else {
            if (index == 0) {
                njBean.setFrontPictureUrl(data.getVisitURL());
            } else if (index == 1) {
                njBean.setSidePictureUrl(data.getVisitURL());
            } else if (index == 2) {
                njBean.setBackPictureUrl(data.getVisitURL());
            }
            size.getAndIncrement();
            if (size.get() == paths.size()) {
               presenter.updateMeshBase(njBean);
            }
        }
    }
    @Override
    public void success() {
        ToastUtils.showShort("修改成功");
        tvTitle.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        },2000);

    }

    @Override
    public void uploadNor(String path, int index) {
        if (index == 0) {
            njBean.setFrontPictureUrl(path);
        } else if (index == 1) {
            njBean.setSidePictureUrl(path);
        } else if (index == 2) {
            njBean.setBackPictureUrl(path);
        }
        size.getAndIncrement();
        if (size.get() == paths.size()) {
            presenter.updateMeshBase(njBean);
        }
    }

    @Override
    public void onZdItemClick(ZdBean zdBean) {
        if (nowClick == 1) {
            tvLeiXing.setText(zdBean.getName());
            type_id=zdBean.getValue();
            brand_parentID = zdBean.getValue();
            tvPinPai.setText("");
            tvxinghao.setText("");
        } else if (nowClick == 2) {
            tvPinPai.setText(zdBean.getName());
            brand_id=zdBean.getValue();
            size_parentID = zdBean.getValue();
            tvxinghao.setText("");
        } else {
            tvxinghao.setText(zdBean.getName());
            size_id=zdBean.getValue();
        }
    }

    private void addFirstIv() {

        View view = LayoutInflater.from(this).inflate(R.layout.item_add_img, null);
        ImageView ivAdd = view.findViewById(R.id.iv_add);
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Matisse.from(DeviceUpdateActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG);
            }
        });
        imgViews.add(view);
        lliv1.addView(view);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_cancle) {
            if (view.getTag() instanceof Uri){
                Uri uri = (Uri) view.getTag();
                if (paths.size() == 3) {
                    for (int i = 0; i < lliv1.getChildCount(); i++) {
                        View child = lliv1.getChildAt(i);
                        if (child.getTag() != null && child.getTag() instanceof Uri) {
                            Uri childUri = (Uri) child.getTag();
                            if (uri.equals(childUri)) {
                                lliv1.removeView(child);
                                imgViews.remove(i);
                                paths.remove(i);
                                break;
                            }
                        }
                    }
                    addFirstIv();
                } else {
                    for (int i = 0; i < lliv1.getChildCount(); i++) {
                        View child = lliv1.getChildAt(i);
                        if (child.getTag() != null && child.getTag() instanceof Uri) {
                            Uri childUri = (Uri) child.getTag();
                            if (uri.equals(childUri)) {
                                lliv1.removeView(child);
                                imgViews.remove(i);
                                paths.remove(i);
                                break;
                            }
                        }
                    }
                }
            }else {
                String uri = (String) view.getTag();
                if (paths.size() == 3) {
                    for (int i = 0; i < lliv1.getChildCount(); i++) {
                        View child = lliv1.getChildAt(i);
                        if (child.getTag() != null && child.getTag() instanceof String) {
                            String childUri = (String) child.getTag();
                            if (uri.equals(childUri)) {
                                lliv1.removeView(child);
                                imgViews.remove(i);
                                paths.remove(i);
                                break;
                            }
                        }
                    }
                    addFirstIv();
                } else {
                    for (int i = 0; i < lliv1.getChildCount(); i++) {
                        View child = lliv1.getChildAt(i);
                        if (child.getTag() != null && child.getTag() instanceof String) {
                            String childUri = (String) child.getTag();
                            if (uri.equals(childUri)) {
                                lliv1.removeView(child);
                                imgViews.remove(i);
                                paths.remove(i);
                                break;
                            }
                        }
                    }
                }
            }

        }
    }


}
